package cn.phecda.boot.tenant.core.liquibase;

import cn.phecda.boot.tenant.core.properties.TenantProperties;
import cn.phecda.boot.tenant.core.service.TenantDataSourceService;
import liquibase.exception.LiquibaseException;
import liquibase.integration.spring.SpringLiquibase;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;

import javax.sql.DataSource;
import java.util.Set;

/**
 * <p> SpringLiquibase租户支持 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
@RequiredArgsConstructor
public class TenantSpringLiquibase implements InitializingBean {
    private final SpringLiquibase springLiquibase;
    private final TenantProperties tenantProperties;
    private final TenantDataSourceService tenantDataSourceService;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (springLiquibase == null) {
            log.info("|Phecda Boot Tenant|- Liquibase database script execution CANCELED, because liquibase is NOT enabled");
            return;
        }

        Set<String> tenantIds = tenantProperties.getDatasources().keySet();
        if (ObjectUtils.isEmpty(tenantIds)) {
            log.info("|Phecda Boot Tenant|- Tenant data source NOT configured, liquibase unable to continue");
            return;
        }

        log.info("|Phecda Boot Tenant|- Tenant data source found {}", tenantIds);
        this.runOnAllTenants(tenantIds, springLiquibase);

    }

    protected void runOnAllTenants(Set<String> tenantIds, SpringLiquibase springLiquibase) throws LiquibaseException {
        for(String tenantId : tenantIds) {
            if (StringUtils.isBlank(tenantId)) {
                continue;
            }

            log.info("|Phecda Boot Tenant|- Initializing liquibase for tenant [{}]", tenantId);

            DataSource ds = tenantDataSourceService.getDataSource(tenantId);
            springLiquibase.setDataSource(ds);
            springLiquibase.afterPropertiesSet();
        }
    }

}
